<template>
	<el-dialog :title="title" width="760" v-model="visible" :close-on-click-modal="false" :destroy-on-close="true" :rules="dataRules" draggable>
		<el-form ref="menuDialogFormRef" :model="form" label-width="90px">
			<div class="blue-card">
				<el-form-item label="资源名称" prop="fileNameCh">
					<el-input v-model="form.fileNameCh" clearable placeholder="请输入" :disabled="disabled"></el-input>
				</el-form-item>
				<el-row :gutter="20">
					<el-col :span="12">
						<el-form-item label="类型" prop="dataSourceType">
							<el-select v-model="form.dataSourceType" placeholder="请选择类型" :suffix-icon="IconDropDown" :disabled="disabled">
								<el-option v-for="item in dataSourceType" :key="item.value" :label="item.label" :value="Number(item.value)" />
							</el-select>
						</el-form-item>
					</el-col>
					<el-col :span="12">
						<el-form-item label="格式" prop="dataType">
							<el-select v-model="form.dataType" placeholder="请选择类型" :suffix-icon="IconDropDown" :disabled="disabled">
								<el-option v-for="item in dataTypeList" :key="item.value" :label="item.label" :value="Number(item.value)" />
							</el-select>
						</el-form-item>
					</el-col>
				</el-row>

				<el-form-item prop="fileRemarks" label="资源描述" class="mt10">
					<el-input type="textarea" placeholder="请输入资源描述" clearable v-model="form.fileRemarks" :disabled="disabled" />
				</el-form-item>
			</div>
			<el-form-item prop="layerNameCh" label="图层名称" class="mt10">
				<el-input placeholder="请输入图层名称" clearable v-model="form.layerNameCh" />
			</el-form-item>
			<el-form-item prop="projectName" label="图层分组">
				<el-select v-model="form.projectName" :suffix-icon="IconDropDown" placeholder="选择所属项目" @change="handleProject">
					<el-option v-for="item in projectOptions" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>
			<el-form-item prop="layerRemarks" label="图层说明">
				<el-input type="textarea" placeholder="请输入图层说明" clearable v-model="form.layerRemarks" />
			</el-form-item>
			<el-form-item label="选择数据" v-if="form.dataSourceType == 2 && form.dataType == 4"> </el-form-item>
			<el-table v-if="form.dataSourceType == 2 && form.dataType == 4" class="table-left" :data="dataList" @filter-change="filterChange">
				<el-table-column prop="tableName" label="图层名称" show-overflow-tooltip />
				<el-table-column
					prop="publishStatus"
					label="发布状态"
					:filters="[
						{ text: '已发布', value: 1 },
						{ text: '未发布', value: 0 },
					]"
					column-key="publishStatus"
					:filter-multiple="false"
				>
					<template #default="scope">
						<el-tag :color="scope.row.publishStatus == 1 ? '#DAF7C9' : '#E8EAF1'">{{ scope.row.publishStatus == 1 ? '已发布' : '未发布' }}</el-tag>
					</template>
				</el-table-column>
				<el-table-column prop="publishStatus" label="选择" width="55">
					<template #default="scope">
						<el-checkbox v-model="scope.row.checked" @change="() => handleSelectionChange(scope.row)"></el-checkbox>
					</template>
				</el-table-column>
			</el-table>
			<div v-if="form.dataType == 4 || form.dataType == 1 || form.dataType == 2" class="blue-card">
				<el-form-item prop="fileNameCh" label="坐标系统">
					<el-select
						filterable
						remote-show-suffix
						remote
						v-model="form.srs"
						:loading="selectLoading"
						:suffix-icon="IconDropDown"
						:remote-method="remoteMethod"
						placeholder="请选择坐标系"
					>
						<el-option v-for="item in srsOptions" :key="item.id" :label="item.name" :value="item.name" />
					</el-select>
				</el-form-item>
				<p></p>
				<div class="mt10">
					<el-text class="mr10 ml20">包围盒边框</el-text>
					<el-row :gutter="20" class="mt10 ml20">
						<el-col :span="6">
							<el-input v-model="form.boxMinX" placeholder="最小X" disabled></el-input>
						</el-col>
						<el-col :span="6">
							<el-input v-model="form.boxMinY" placeholder="最小Y" disabled></el-input>
						</el-col>
						<el-col :span="6">
							<el-input v-model="form.boxMaxX" placeholder="最大X" disabled></el-input>
						</el-col>
						<el-col :span="6">
							<el-input v-model="form.boxMaxY" placeholder="最大Y" disabled></el-input>
						</el-col>
					</el-row>
				</div>
				<div class="mt10">
					<el-text class="mr10 ml20">经纬度边框</el-text>
					<el-row :gutter="20" class="mt10 ml20">
						<el-col :span="6">
							<el-input v-model="form.latLonBoxMinX" placeholder="最小X" disabled></el-input>
						</el-col>
						<el-col :span="6">
							<el-input v-model="form.latLonBoxMinY" placeholder="最小Y" disabled></el-input>
						</el-col>
						<el-col :span="6">
							<el-input v-model="form.latLonBoxMaxX" placeholder="最大X" disabled></el-input>
						</el-col>
						<el-col :span="6">
							<el-input v-model="form.latLonBoxMaxY" placeholder="最大Y" disabled></el-input>
						</el-col>
					</el-row>
				</div>
				<div class="text-center">
					<el-button class="sum-btn" type="primary" @click="borderCalculation">计算</el-button>
				</div>
			</div>
			<el-form-item v-if="form.dataSourceType == 2" prop="styleName" label="图层样式" class="mt10">
				<el-select v-model="form.styleName" :suffix-icon="IconDropDown" placeholder="选择图层样式" clearable>
					<el-option v-for="item in styleOptions" :key="item.value" :label="item.label" :value="item.value" />
				</el-select>
			</el-form-item>
			<div class="text-center">
				<el-button @click="close()">取消</el-button>
				<el-button type="primary" @click="onSubmit(menuDialogFormRef)">保存</el-button>
			</div>
		</el-form>
	</el-dialog>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { addPost, editPost, getCoordinatelist, getStyle, saveSubmit } from '/@/api/project';
import {
	addGeoLayer,
	getInfoById,
	updateGeoLayer,
	getBorderCalculation,
	getGeoBoxLatLonData,
	getTableDataSourceInfo,
	getAllWorkSpaceList,
} from '/@/api/resource/layerManagement';
import { useMessage } from '/@/hooks/message';
import { useUserInfo } from '/@/stores/userInfo';
import DropDown from '/@/assets/icons/drop-down.svg';

const visible = ref(false);
const menuDialogFormRef = ref('');
const emit = defineEmits(['refresh']);
const title = ref('发布图层');
const styleOptions = ref<any[]>([]);
const form = ref({});
const disabled = ref(false);
const selectLoading = ref(false);

const dataList = ref([]);
const loading = ref(false);
const state = reactive({});

const IconDropDown = {
	render: () => {
		return h('img', { src: DropDown });
	},
};

let checkedTable = ref({}); // 存储当前数据
let checkedTableId = null; // 存储当前数据的ID
const srsOptions = ref<any[]>([]);
const checkedCities = ref([]);
const checkList = reactive([
	{
		label: '顶点压缩(有损压缩，如果模型有变形，可取消该选项)',
		value: 0,
	},
	{
		label: '使用实例(Instance)',
		value: 1,
	},
	{
		label: '压缩b3dm',
		value: 2,
	},
	{
		label: '公共纹理嵌入',
		value: 3,
	},
]);
const headers = computed(() => {
	return {
		Accept: 'application/octet-stream',
	};
});

const dataTypeList = ref([
	// 基本底图
	{
		label: '瓦片地图',
		value: '6',
		tip: '选择本地zip格式文件路径上传',
		accept: ['zip'],
	},
	{
		label: '地形',
		value: '7',
		tip: '选择本地zip格式文件路径上传',
		accept: ['zip'],
	},
	{
		label: 'WMS服务',
		value: '8',
		tip: '选择本地zip格式文件路径上传',
		accept: ['zip'],
	},
	// 二维
	{
		label: 'Shapefile',
		value: '1',
		tip: '选择本地zip格式文件路径上传',
		accept: ['zip'],
	},
	{
		label: 'Tif',
		value: '2',
		tip: '选择本地fbx、glb格式文件路径上传',
		accept: ['tif', 'tiff'],
	},
	{
		label: 'PostGIS',
		value: '4',
		tip: '选择本地zip格式文件路径上传',
		accept: ['zip'],
	},
	// 三维
	{
		label: '3Dtiles',
		value: '3',
		tip: '选择本地zip格式文件路径上传',
		accept: ['zip'],
	},
	{
		label: 'FBX/GLB',
		value: '5',
		tip: '选择本地fbx、glb格式文件路径上传',
		accept: ['tif', 'tiff'],
	},
]);

const dataSourceType = ref<any[]>([
	{ label: '基础底图', value: '1' },
	{ label: '二维矢量', value: '2' },
	{ label: '三维模型', value: '3' },
]);

// 表单校验规则
const dataRules = reactive({
	projectName: [{ required: true, message: '图层分组不能为空', trigger: 'blur' }],
	srs: [{ required: true, message: '坐标系不能为空', trigger: 'blur' }],
	layerRemarks: [{ required: true, message: '样式说明不能为空', trigger: 'blur' }],
});

const projectOptions = ref([]);

const coorForm = ref({
	size: 100,
	current: 1,
	name: '',
});
// 获取坐标系方法
function remoteMethod(val) {
	if (form.value.dataSourceType == 3) return;
	selectLoading.value = true;
	coorForm.value.name = val;
	getCoordinatelist(coorForm.value).then((res) => {
		let { data } = res;
		srsOptions.value = data.records;
		selectLoading.value = false;
	});
}

// 获取样式
async function handleProject(projectName: any) {
	if (form.value.dataSourceType == 3) return;
	const { data } = await getStyle({ projectName });
	styleOptions.value = data.map((item: any) => {
		return {
			label: item.styleNameCh,
			value: item.styleName,
		};
	});
}

// 边框计算
const borderCalculation = async () => {
	if (!form.value.srs) {
		useMessage().error('请选择坐标系统！');
		return;
	}

	try {
		loading.value = true;
		const { data } = await getBorderCalculation({
			columnName: checkedTable.value.columnName,
			tableName: checkedTable.value.tableName,
			wokeSpaceName: form.value.wokeSpaceName,
			storeName: form.value.storeName,
			srs: form.value.srs,
		});
		form.value.latLonBoxMinX = data.boxMinx;
		form.value.latLonBoxMinY = data.boxMiny;
		form.value.latLonBoxMaxX = data.boxMaxx;
		form.value.latLonBoxMaxY = data.boxMaxy;
		LatLonCalculation();
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};
// 经纬度计算
const LatLonCalculation = async () => {
	try {
		loading.value = true;
		const { data } = await getGeoBoxLatLonData({
			srs: form.value.srs,
			boxMinx: form.value.boxMinX,
			boxMiny: form.value.boxMinY,
			boxMaxx: form.value.boxMaxX,
			boxMaxy: form.value.boxMaxY,
		});
		form.value.boxMinX = data.boxMinx;
		form.value.boxMinY = data.boxMiny;
		form.value.boxMaxX = data.boxMaxx;
		form.value.boxMaxY = data.boxMaxy;
	} catch (err: any) {
		useMessage().error(err.msg);
	} finally {
		loading.value = false;
	}
};

// 选择数据
const handleSelectionChange = (row) => {
	checkedTable.value = row;
	// console.log(checkedTable.value, '当前项');

	if (checkedTableId === row.tableName) {
		checkedTableId = null;
		checkedTable.value = {};
	} else {
		checkedTableId = row.tableName;
	}

	dataList.value.forEach((item) => {
		item.checked = item.tableName === checkedTableId;
	});

	// 获取当前勾选项
	getTableCheckedItem();
	if (row.dataType == 4) {
		state.dataSourceId = row.dataSourceId;
		getTableList();
	}
};
const getTableCheckedItem = () => {
	if (checkedTableId !== null) {
		const currentItem = dataList.value.find((item) => item.tableName === checkedTableId);
	} else {
		checkedTable.value = {};
		// console.log('没有勾选项');
	}
};

const close = () => {
	visible.value = false;
	form.value = {};
};

//表单提交
const onSubmit = async (forms) => {
	await forms.validate((valid) => {
		if (valid) {
			// shp类型是文件上传的，serviceType就传1
			if (form.value.fileId && form.value.dataSourceType == 2) {
				form.value.serviceType = 1; // 1-在线图层，2-静态服务
			} 
			// postGIS
			if (form.value.dataType == 4) {
				form.value.serviceType = 1;
				form.value.storeName = form.value.fileDataName;
				form.value.layerName = checkedTable.value.tableName;
				form.value.dataSourceId = state.dataSourceId;
			}

			// 删除多余参数
			const propertiesToDelete = [
				'onEnable',
				'defaultStr',
				'wokeSpaceBack',
				'fileId',
				'fileDataName',
				'projectNameCh',
				'fileRemarks',
				'fileNameCh',
				'createTime',
				'updateTime',
				'dataSourceName',
				'sourceServiceUrl',
				'host',
				'port',
				'username',
				'databaseName',
				'password',
				'checked',
				'uploadStatus',
				'fileUid',
			];

			for (const prop of propertiesToDelete) {
				delete form.value[prop];
			}
			saveSubmit(form.value)
				.then((res) => {
					if (res.code == 0) {
						useMessage().success(res.msg);
						visible.value = false;
						reset();
						emit('refresh');
					} else if (res.code == 1) {
						return;
					}
				})
				.catch((res) => {
					// console.log('报错---');
					// useMessage().error(res.msg);
				});
		}
	});
};

const filterChange = (filter) => {
	state.publishStatus = filter.publishStatus.join(',');
	getTableList(state);
};

//重置表单
const reset = () => {
	form.value = {
		wokeSpaceName: '',
		onEnable: true,
		defaultStr: false,
		wokeSpaceBack: '',
	};
};
function openDialog(row: any) {
	disabled.value = false;
	visible.value = true;
	// 获取坐标系统
	remoteMethod();
	nextTick(() => {
		form.value.storeName = row.fileDataName;
		disabled.value = true;
		Object.assign(form.value, row);
	});

	if (row.dataType == 4) {
		state.dataSourceId = row.dataSourceId;
		getTableList();
	}
	getAllWorkSpaceList({}).then((res) => {
		let { data } = res;
		projectOptions.value = data.map((item) => {
			return {
				label: item.projectNameCh,
				value: item.wokeSpaceName,
			};
		});
	});
}

const getTableList = async (id) => {
	await getTableDataSourceInfo(state).then((res) => {
		dataList.value = res.data;
	});
};

defineExpose({
	openDialog,
	reset,
});
</script>
<style scoped lang="scss">
.text-center {
	text-align: right;
	margin-top: 18px;
}
.preview {
	position: absolute;
	left: 110px;
	color: #0768ad;
	text-decoration: underline;
}
.sum-btn {
	width: 180px;
}
p {
	width: 97%;
	text-align: center;
	border-bottom: 1px solid #1580cd;
	line-height: 1px;
	margin: 8px 20px;
}
.blue-card {
	margin: 5px 5px 20px 5px;
	padding: 10px;
	background: #edf0f7;
	padding-left: 0px;
}
.table-left {
	width: 98.6%;
	height: 180px;
	margin: auto;
	border: 1px solid #3156a5;
}
</style>
